/**
 * This program is free software but WITHOUT ANY WARRANTY OR CONDITIONS OF ANY KIND.
 *
 * Copyright (C) 2011 www.pretty-tools.com
 */

var wwwPrettyTools_KlassButtonToollbar = {
    TOOLBAR_BUTTON_ID: "Klass_Button_Pretty_Tools",
    DIV_ID: "ButtonKlassByPrettyToolsDiv",
    API_URL: "http://www.odnoklassniki.ru/dk?st.cmd=addShare&st.s=1000&st._surl=",
    GET_VOTES_URL: "http://www.odnoklassniki.ru/dk?st.cmd=shareData&cb=mailru.share.ok.init&ref=",
    SUCCESSFULLY_INSTALLED_URL: "http://odnoklassniki.pretty-tools.com/installed_for_firefox.htm",
    SHARE_BUTTONS_FRAME_DOMAIN: "http://connect.mail.ru/share_button",
    KLASS_BUTTONS_CLASSES_NAMES: ["odkl-klass-stat", "odkl-share-stat", "odkl-klass-oc-voted", "odkl-share-oc-voted", "odkl_share_stat"]
};

wwwPrettyTools_KlassButtonToollbar.onLoad = function(event)
{
    try
    {
        window.addEventListener("pageshow", function(e) {
            wwwPrettyTools_KlassButtonToollbar.onPageShow(e);
        }, false);

        gBrowser.mTabContainer.addEventListener("select", function(e) {
            wwwPrettyTools_KlassButtonToollbar.updateToolbarButton();
        }, false);

        if (wwwPrettyTools_KlassButtonConfiguration.isFirstStart()) { // execute following only one time just after installation
            // add button to navigation panel
            this.installButtonOnToolbar();
            // need to open page with instructions
            setTimeout(function() {
                // open page with instructions
                gBrowser.selectedTab = gBrowser.addTab(wwwPrettyTools_KlassButtonToollbar.SUCCESSFULLY_INSTALLED_URL);
            }, 2000);
        }
    }
    catch(ex)
    {
        dump("Exception during onLoad: " + ex + "\n");
    }
}

wwwPrettyTools_KlassButtonToollbar.installButtonOnToolbar = function ()
{
    try
    {
        var btn = document.getElementById(this.TOOLBAR_BUTTON_ID);
        if (btn) // button exists
            return;

        // let's add it
        var navBar = document.getElementById("nav-bar");
        if (!navBar)
            return;

        var currentSet = navBar.getAttribute("currentset");
        if (!currentSet)
            currentSet = navBar.currentSet;

        var curSet = currentSet.split(",");
        if (curSet.indexOf(this.TOOLBAR_BUTTON_ID) == -1)
        {
            var set = curSet.concat(this.TOOLBAR_BUTTON_ID);
            navBar.setAttribute("currentset", set.join(","));
            document.persist("nav-bar", "currentset");
        }

        navBar.insertItem(this.TOOLBAR_BUTTON_ID);
    }
    catch(ex)
    {
        dump("Exception during installButtonOnToolbar: " + ex + "\n");
    }
}

wwwPrettyTools_KlassButtonToollbar.onPressButton = function ()
{
    try
    {
        var doc = window.content.document;

        if (!doc || !doc.location || !doc.location.href || !doc.location.href.match(/^http/))
            return;

        var url = this.API_URL + encodeURIComponent(doc.location.href);

        if (!wwwPrettyTools_KlassButtonConfiguration.isOpenInPopup())
            gBrowser.selectedTab = gBrowser.addTab(url);
        else
        {
            var left = (screen.width / 2) - (350);
            var top = (screen.height / 2) - (250);

            window.open(url, "_blank", "top="+top+",left="+left+",width=700,height=500,resizable=1");
        }
    }
    catch(e)
    {
        dump("Exception during onPressButton: " + e + "\n");
    }
}

wwwPrettyTools_KlassButtonToollbar.parseVotesResponse = function (txt)
{
    try
    {
        if (!txt)
            return "";

        var LOOK_FOR = '"count":';
        var idx = txt.indexOf(LOOK_FOR);
        if (idx == -1)
            return "";

        idx = txt.indexOf('"', idx + LOOK_FOR.length);
        if (idx == -1)
            return "";

        var idx2 = txt.indexOf('"', idx + 1);
        if (idx2 == -1)
            return "";

        var votes = txt.substring(idx + 1, idx2);

        for (var i = votes.length-3; i > 0; i -= 3)
            votes = votes.substr(0, i) + " " + votes.substr(i);

        return (votes.length > 0 && votes.length <= 16) ? votes : "";
    }
    catch(ex)
    {
        return null;
    }
}

wwwPrettyTools_KlassButtonToollbar.cacheVotesFromElementById = function (doc, elementId, saveToDoc)
{
    try {
        return this.cacheVotesFromChildSpan(doc.getElementById(elementId), saveToDoc);
    } catch(ex) {}
}

wwwPrettyTools_KlassButtonToollbar.cacheVotesFromElementByClassName = function (doc, className)
{
    try
    {
        var elements = doc.getElementsByClassName(className);

        for (var idx in elements)
        {
            this.cacheVotesFromChildSpan(elements[idx], doc);
        }
    }
    catch(ex)
    {
    }
}

wwwPrettyTools_KlassButtonToollbar.cacheVotesFromElementByClassesName = function (doc, classsesNames)
{
    try
    {
        for (var idx in classsesNames)
        {
            this.cacheVotesFromElementByClassName(doc, classsesNames[idx]);
        }
    }
    catch(ex)
    {
    }
}

wwwPrettyTools_KlassButtonToollbar.cacheVotesFromChildSpan = function (shareCounter, saveToDoc)
{
    try
    {
        if (!shareCounter)
            return;

        for (var childIdx in shareCounter.childNodes)
        {
            var child = shareCounter.childNodes[childIdx];

            if (child.tagName != "SPAN")
                continue;

            var votes = child.textContent;
            if (!votes.length || votes.length > 16)
                continue;

            var idx = votes.indexOf(" и ");
            if (idx != -1) // It's in format You and 1, so we need to plus one to specified count
            {
                votes = votes.substring(idx + 3, votes.length);
                votes = votes.replace(/ /g, "");

                votes = "" + (Number(votes) + 1);

                // add spaces
                for (var i = votes.length-3; i > 0; i -= 3)
                    votes = votes.substr(0, i) + " " + votes.substr(i);
            }

            wwwPrettyTools_KlassButtonToollbar.cacheVotes(!saveToDoc ? doc : saveToDoc, votes);
            break;
        }
    }
    catch(ex)
    {
    }
}

wwwPrettyTools_KlassButtonToollbar.onPageShow = function (event)
{
    try
    {
        var doc = event.target;

        var href = doc.location.href;

        if (!href.match(/^http/) || !(event.originalTarget instanceof HTMLDocument))
            return;

        if (!event.originalTarget.defaultView.frameElement) // skip frames
        {
            this.cacheVotesFromElementByClassesName(doc, this.KLASS_BUTTONS_CLASSES_NAMES);

            if (wwwPrettyTools_KlassButtonConfiguration.getShowVotes() == 1)
            {
                if (doc.getElementsByClassName("odkl-klass-oc").length > 0 // button exists but it's not yet initialized
                        || doc.getElementsByClassName("odkl-share-oc").length > 0)
                {
                    setTimeout(function () {
                        wwwPrettyTools_KlassButtonToollbar.cacheVotesFromElementByClassesName(doc, wwwPrettyTools_KlassButtonToollbar.KLASS_BUTTONS_CLASSES_NAMES);
                        wwwPrettyTools_KlassButtonToollbar.updateToolbarButton();
                    }, 1500);
                    setTimeout(function () {
                        wwwPrettyTools_KlassButtonToollbar.cacheVotesFromElementByClassesName(doc, wwwPrettyTools_KlassButtonToollbar.KLASS_BUTTONS_CLASSES_NAMES);
                        wwwPrettyTools_KlassButtonToollbar.updateToolbarButton();
                    }, 3000);
                }
            }
            else if (wwwPrettyTools_KlassButtonConfiguration.getShowVotes() == 2 // always get votes
                        && !doc.getElementById(this.DIV_ID) /* Not yet cached */)
            {
                var url = href; // we need to remove '/' at the end of URL
                if (url.charAt(url.length-1) == '/')
                    url = url.substring(0, url.length-1);

                var req = new XMLHttpRequest();
                req.open('GET', this.GET_VOTES_URL + encodeURIComponent(url), true);

                try {
                    req.channel.loadFlags |= Components.interfaces.nsIRequest.LOAD_ANONYMOUS;
                } catch (e) {
                }

                req.onreadystatechange = function (evt)
                {
                    if (req.readyState != 4 || req.status != 200)
                        return;

                    try
                    {
                        var votes = wwwPrettyTools_KlassButtonToollbar.parseVotesResponse(req.responseText);

                        wwwPrettyTools_KlassButtonToollbar.cacheVotes(doc, votes);
                        wwwPrettyTools_KlassButtonToollbar.updateToolbarButton();
                    }
                    catch(ex)
                    {
                    }
                };

                req.send(null);
            }

            this.updateToolbarButton();
        }
        else if (href.indexOf(this.SHARE_BUTTONS_FRAME_DOMAIN) != -1) // otherwise it's frame with counter
        {
            this.cacheVotesFromElementById(doc, "ok-share-counter", event.originalTarget.defaultView.parent.document);
            this.updateToolbarButton();
        }
    }
    catch(ex)
    {
        dump("Exception during onPageShow: " + ex + "\n");
    }
}

wwwPrettyTools_KlassButtonToollbar.updateToolbarButton = function ()
{
    try
    {
        var btn = document.getElementById(this.TOOLBAR_BUTTON_ID);
        if (!btn)
            return;

        var div = window.content.document.getElementById(this.DIV_ID);
        if (!div)
        {
            btn.setAttribute("label", "");
        }
        else if (wwwPrettyTools_KlassButtonConfiguration.getShowVotes() > 0)
        {
            var txt = div.innerText;

            if (txt == "0" && !wwwPrettyTools_KlassButtonConfiguration.isShowZeros())
                txt = "";

            btn.setAttribute("label", txt);
        }
    }
    catch(e)
    {
        dump("Exception during updateToolbarButton: " + e + "\n");
    }
}

wwwPrettyTools_KlassButtonToollbar.cacheVotes = function (doc, votes)
{
    try
    {
        var div = null;
        if (!(div = doc.getElementById(this.DIV_ID)))
        {
            div = doc.createElement('div');
            div.id = this.DIV_ID;
            // hide button
            div.style.position = "absolute";
            div.style.filter = "alpha(opacity: 0)";
            div.style.opacity = "0";
            div.style.zIndex = "-1";
            div.style.width = "1px";
            div.style.maxWidth = "1px";
            div.style.height = "1px";
            div.style.maxHeight = "1px";
            div.style.top = "0";
            div.style.left = "0";

            doc.body.appendChild(div);
        }
        div.innerText = votes;
    }
    catch(ex)
    {
        dump("Exception during cacheVotes: " + ex + "\n");
    }
}

try
{
    addEventListener("load", function(event) {
        try {
            wwwPrettyTools_KlassButtonToollbar.onLoad(event);
        } catch(ex) {
            dump("Exception on inilializing KlassButtonToollbar.js: " + ex + "\n");
        }
    }, false);
}
catch(ex)
{
    dump("Exception on inilializing KlassButtonToollbar.js: " + ex + "\n");
}
